package org.mentalsmash.crossroads.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;

/**
 * 
 * @author Andrea Reale
 * Mantains a Pair (PageTitle,URL) for a web search result
 */
public class WebSearchResult {
    private static Logger log = Logger.getLogger(WebSearchResult.class);
	private String _pageTitle;
	private URL _pageURL;
	
	/**
	 * Constructor for a pair (title,url)
	 * @param pageTitle the title for the page
	 * @param pageURL the url of the page
	 */
	public WebSearchResult(String pageTitle, URL pageURL) {
		_pageTitle = pageTitle;
		_pageURL = pageURL;
	}
	/**
	 * Get the title of the page for this web search result
	 * @return the title as returned by Google Web Search
	 */
	public String getPageTitle() {
		return _pageTitle;
	}
	
	/**
	 * Get the URL associated to this web result
	 * @return the URL (usually an http web page) associated with this web search result as returned by Google
	 */
	public URL getPageURL() {
		return _pageURL;
	}
	
	/**
	 * Fetches a page by connecting to the URL associated to the WebSearch Result
	 * @return A string containing the response from the connection
	 * @throws PageFetchException If for any reason the page cannot be fetched (e.g. it is a remote URL and you cannot connect to the Internet)
	 */
	public String fetchPage() throws PageFetchException
	{
		if (getPageURL() == null)
			throw new PageFetchException("Unable to fetch result: null URL");

		StringBuilder builder;
		try {
			log.debug("Fetching page at URL: " + getPageURL().toString());
			URLConnection connection = getPageURL().openConnection();
			String line;
			builder = new StringBuilder();

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			while((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e)
		{
			throw new PageFetchException("Error fetching page",e);
		}
		
		String response = builder.toString();
		//log.debug("Response form URL was:" + response);
		return response;

	}
	
	@Override
	/**
	 * The hascode of a web result is the hascode of the page's URL
	 */
	public int hashCode() {
		return _pageURL.hashCode();
	}
	

	@Override
	/**
	 * Two webresults are the same result if they are the same object, or if they have the same title, and they refer to the same URL
	 */
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		WebSearchResult other = (WebSearchResult) obj;
		if (_pageTitle == null) {
			if (other._pageTitle != null)
				return false;
		} else if (!_pageTitle.equals(other._pageTitle))
			return false;
		if (_pageURL == null) {
			if (other._pageURL != null)
				return false;
		} else if (!_pageURL.equals(other._pageURL))
			return false;
		return true;
	}
	
	
	
}
